define [
  'controllers/base/controller'
  'views/user/login_view'
  'views/user/index_view'
  'views/user/form_view'
  'models/user_model'
  'collections/user_collection'
  'daos/access_dao'
  'daos/user_dao'
  'lib/dao_factory'
], () ->

  'use strict'

  # Imports
  # =============================================================

  Controller                  = require 'controllers/base/controller'
  UserModel                   = require 'models/user_model'
  UserCollection              = require 'collections/user_collection'
  LoginView                   = require 'views/user/login_view'
  DaoFactory                  = require 'lib/dao_factory'
  IndexView                   = require 'views/user/index_view'
  FormView                    = require 'views/user/form_view'

  # DAO's
  # =============================================================

  AccessDAO      = DaoFactory.getDAOByName 'access_dao'
  UserDAO        = DaoFactory.getDAOByName 'user_dao'

  class UserController extends Controller

    # Actions
    # =============================================================

    beforeAction: ->
      super
      @model = new UserModel

    index: ->
      console.log @globals.userData
      if @globals.userData.tipoUsuario is  'ADMINISTRADOR'
        @collection = new UserCollection
        @view       = new IndexView collection: @collection
      else
        @redirectTo url: 'usuario/' + @globals.userData.id

    login: (params) ->
      @view  = new LoginView model: @model

      _signin = (formData) =>
        return if !formData.username and !formData.password

        @model.set 'username', formData.username

        promise = AccessDAO.login formData.username, formData.password
        promise.done => @redirectTo url: 'usuario/index'
        promise.fail (response) =>
          @publishEvent 'feedback:error', 'Usuário e(ou) senha inválido(s)'

          @view.enableActions()

      # Login
      @view.on 'signin', _signin

    logout: ->
      AccessDAO.logout()
      @redirectTo url: ''

    create: ->
      @model = new UserModel
      @view  = new FormView
        model: @model
        isNovoUsuario: false
      @_setupHistoryBack()

    novo: ->
      @model = new UserModel
      @view  = new FormView
        model: @model
        isNovoUsuario: true
      @_setupHistoryBack()

    edit: (params) ->
      @model = new UserModel id: params.id
      @view  = new FormView model: @model
      @_setupHistoryBack()

    _setupHistoryBack: ->
      @view.on 'model:saved', =>
        @publishEvent 'feedback:success', 'Usuário salvo com sucesso'
        @redirectTo url: 'usuario'
